package com.lanou3g.springmvc.web;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.List;

/**
 * 使用流的方式直接操作请求、响应
 */
@Controller
public class TestStreamController {


    @RequestMapping("/stream")
    public String testHttpEntity(HttpEntity<String> entity, HttpServletRequest req) {
        // 使用HttpEntity对象方式获取请求头、请求体数据
        HttpHeaders headers = entity.getHeaders();
        Object body = entity.getBody();
        System.out.println("请求头参数列表：");
        for(String header : headers.keySet()) {
            List<String> values = headers.get(header);
            String value = Arrays.toString(values.toArray());
            System.out.println(header + ": " +value);
        }

        System.out.println("请求体：");
        System.out.println(body);
        System.out.println("---------------------------------------------");

        // 使用request对象方式获取请求头、请求体数据
        System.out.println("请求头参数列表：");

        Enumeration<String> headerNames = req.getHeaderNames();

        for(;headerNames.hasMoreElements();) {
            String headerName = headerNames.nextElement();
            String value = req.getHeader(headerName);
            System.out.println(headerName + ": " +value);
        }

        System.out.println("请求体：");
        Enumeration<String> parameterNames = req.getParameterNames();
        for(;parameterNames.hasMoreElements();) {
            String bodyKey = parameterNames.nextElement();
            String bodyValue = req.getParameter(bodyKey);
            System.out.println(bodyKey + ": " +bodyValue);
        }
        return "index2";
    }

    /*@RequestMapping("/stream")
    public void testStream(Reader reader, OutputStream out, Thread thread) {
        try {
            BufferedReader br = new BufferedReader(reader);
            String inputStr = br.readLine();
            System.out.println("请求的数据：" + inputStr);
        } catch (IOException e) {
            e.printStackTrace();
        }

        *//*ByteArrayOutputStream in_ = new ByteArrayOutputStream();
        try {
            copyStream(in, in_);

            // 获取请求数据
            byte[] inputData = in_.toByteArray();
            String input = new String(inputData, "UTF-8");

            System.out.println("input: " + input);
        } catch (IOException e) {
            e.printStackTrace();
        }*//*
    }*/

    private void copyStream(InputStream in, OutputStream out) throws IOException {
        byte[] buffer = new byte[1024];
        int len = -1;
        while (in.read(buffer) != -1) {
            out.write(buffer, 0, len);
        }
        out.flush();
        out.close();
        in.close();
    }

}
